<?php
/**
 * 用户验证
 */
declare (strict_types=1);

namespace app\services;


use app\model\LoginLog;
use app\model\User;
use app\services\CacheServices;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use utils\JwtAuth;

class UserAuthServices extends BaseServices
{

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    /**
     * 获取授权信息
     * @param $token
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function parseToken($token)
    {
        if ($token === 'undefined' || !$token) {
            throw new HttpException(401, '请登录');
        }
        $jwtAuth = app()->make(JwtAuth::class);
        // 解析token
        [$uid, $type] = $jwtAuth->parseToken($token);
        $cacheServices = Cache::store('redis');
        $md5Token = md5('apiToken:' . $uid);
        $tokenData = $cacheServices->get($md5Token);
        if (!$tokenData) {
            throw new HttpException(401, '登录过期，请重新登录');
        }
        if (!is_array($tokenData) || empty($tokenData) || !isset($tokenData['uid'])) {
            throw new HttpException(401, '登录有误，请重新登录');
        }
        //验证token
        try {
            $jwt = $jwtAuth->verifyToken($token);
        } catch (\Throwable $e) {
            $cacheServices->delete($md5Token);
            throw new HttpException(401, '登录已过期,请重新登录');
        }
        $user = $this->model->where('id', $uid)->where('status', 1)->find(); // 获取用户信息
        if (empty($user) || $user->id != $tokenData['uid']) {
            throw new HttpException(401, '登录状态有误,请重新登录');
        }
        if ($user->login_time != $jwt['user']['login_time']) {
            throw new HttpException(402, '当前账号在另一设备上登陆，若非本人操作，您的登陆密码可能泄露，请及时修改密码'); // 账号在另一设备登录
        }
        return $user;
    }


    /**
     * 用户信息
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function UserInfo($data)
    {
        try {
            $user = $this->model->field('id,p_id,avatar,nickname,phone,username,is_real_name,card_num,integral,code,start_id,login_time,login_ip,created_time,updated_time,status,money,password,paypass,vip,vip_time')->where(['phone' => $data['phone']])->find();
            if (!$user) {
                return array('code' => 500, 'msg' => '用户不存在');
            }
            if ($user->status == 0) {
                return array('code' => 500, 'msg' => '账号已被禁用');
            }


            if (isset($data['cls']) && ($data['cls'] == 1 || $data['cls'] == 2) && sha1($data['password']) != $user->password) {
                $user->login_ip = $data['ip'];
                $user->login_time = date('Y-m-d H:i:s', time());
                $user->save();
                return array('code' => 500, 'msg' => '登录密码错误');
            }
            $result = $user->toArray();
            $result['domain'] = SystemConfig('qnoss_domain') . '/';
            $result['avatar'] = $result['domain'] . $result['avatar'];
            $result['contribution'] = Db::name('money_log')->where(['user_id' => $user->id, 'state' => 2])->sum('money');
            $result['openid'] = '';
            $result['session_key'] = '';
        } catch (\Exception $exception) {
            return array('code' => 500, 'msg' => '登录失败' . $exception->getMessage());
        }
        return array('code' => 200, 'data' => $result);
    }
}